/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.spreadsheet;

import cn.ac.nercis.pes.community.component.controls.PesCheckComboBox;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.input.KeyCode;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.controlsfx.control.spreadsheet.SpreadsheetCellEditor;
import org.controlsfx.control.spreadsheet.SpreadsheetView;

import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 单元格多选列表编辑器控件
 * @author zpy
 * @version 1.0.0
 */
public class PesCheckComboBoxCellEditor<T>  extends SpreadsheetCellEditor {
    private final ObservableList<T> itemList;
    private final PesCheckComboBox<T> cb;
    private String originalValue;

    /**
     * Constructor for the ListEditor.
     * @param view The SpreadsheetView
     * @param itemList The items to display in the editor.
     */
    public PesCheckComboBoxCellEditor(SpreadsheetView view, final ObservableList<T> itemList,String splitChar) {
        super(view);
        this.itemList = itemList;
        cb = new PesCheckComboBox<>(itemList,splitChar);
    }

    @Override
    public void startEdit(Object value, String format, Object... options) {
        if (Objects.nonNull(value)) {
            originalValue = value.toString();
        } else {
            originalValue = null;
        }
        this.refreshItemSelected();

        attachEnterEscapeEventHandler();
        cb.show();
        cb.requestFocus();
    }

    @Override
    public void end() {
        cb.setOnKeyPressed(null);
    }

    @Override
    public PesCheckComboBox<T> getEditor() {
        return cb;
    }

    @Override
    public String getControlValue() {
        if(Objects.isNull(cb.getCheckModel()) || CollectionUtils.isEmpty(cb.getCheckModel().getCheckedItems())){
            return StringUtils.EMPTY;
        }
        return cb.getCheckModel().getCheckedItems().stream()
                .filter(Objects::nonNull)
                .map(Object::toString)
                .collect(Collectors.joining(cb.getJoinChar()));
    }

    public ObservableList<T> getValue(){
        if(Objects.isNull(cb.getCheckModel())){
            return FXCollections.emptyObservableList();
        }
        return cb.getCheckModel().getCheckedItems();
    }
    private void attachEnterEscapeEventHandler() {
        cb.setOnKeyPressed(t -> {
            if (t.getCode() == KeyCode.ESCAPE) {
                this.refreshItemSelected();
                endEdit(false);
            } else if (t.getCode() == KeyCode.ENTER) {
                endEdit(true);
            }
        });
    }

    private void refreshItemSelected(){
        if(Objects.nonNull(cb.getCheckModel()) && StringUtils.isNotEmpty(originalValue)){
            cb.getCheckModel().clearChecks();
            var selected = Arrays.asList(StringUtils.split(originalValue,cb.getJoinChar()));
            itemList.stream()
                    .filter(item->selected.stream().anyMatch(s->StringUtils.equals(s,item.toString())))
                    .forEach(v-> cb.getCheckModel().check(v));
        }
    }
}